<?php

namespace handle\message\lib\manage;

use Exception;
use handle\message\lib\manage\lib\Room;
use handle\message\lib\traits\ManageObserver;

class RoomManage
{
    use ManageObserver;

    /**
     * 创建房间
     * @param string $room_id       房间ID
     * @return Room
     */
    public function create(string $room_id): Room
    {
        if(!isset($this->observer[$room_id]) or empty($this->observer[$room_id])) {
            $this->observer[$room_id] = new Room($room_id);
            $this->observer[$room_id]->setManage(self::$instance);
            $this->observer[$room_id]->init();
        }
        return $this->observer[$room_id];
    }
    /**
     * 进入房间
     * @param string $room_id       房间ID
     * @param int $uid
     * @return void
     * @throws Exception
     */
    public function enterRoom(string $room_id, int $uid){
        $this->get($room_id)->addPlayer($uid);
    }

    /**
     * 退出房间
     * @param string $room_id
     * @param int $uid
     * @return void
     * @throws Exception
     */
    public function exitRoom(string $room_id, int $uid){
        $this->get($room_id)->exitRoom($uid);
    }

    /**
     * 判断房间是否可以开始游戏
     * @param string $room_id
     * @return bool
     * @throws Exception
     */
    public function isCanStartGame(string $room_id): bool
    {
        return count($this->get($room_id)->getPlayerInfo()) == 2;
    }

    /**
     * 开始游戏
     * @param string $room_id       房间ID
     * @return void
     * @throws Exception
     */
    public function startGame(string $room_id){
        $this->get($room_id)->startGame();
    }

    /**
     * 设置胜负状态
     * @param string $room_id 房间ID
     * @param int $outcome  对局结果
     * @return void
     * @throws Exception
     */
    public function setOutcome(string $room_id, int $outcome){
        $this->get($room_id)->setOutcome($outcome);
    }

    /**
     * 获取房间状态
     * @param string $room_id
     * @return int
     * @throws Exception
     */
    public function getRoomStatus(string $room_id): int
    {
        return $this->get($room_id)->getStatus();
    }

}